package domain.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.data.QnAPersistenceManager;
import domain.model.Keyword;

@SuppressWarnings("serial")
public class TopicServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		String ip = req.getRemoteAddr();

        req.setAttribute("ip", ip);		
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        if(count != 2)
        {
        	resp.sendRedirect("/");
        }
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		title_url=URLDecoder.decode(title_url,"UTF-8");
		
		Query query = psm.newQuery(Keyword.class);
		query.setFilter("name=='"+title_url+"'");
		@SuppressWarnings("unchecked")
		List<Keyword> keywords = (List<Keyword>) query.execute();
		if(keywords.size() > 0)
		{
			req.setAttribute("keywords", keywords);
			req.setAttribute("topic", title_url);
			
			req.setAttribute("title", "Topic - "+title_url);
			req.setAttribute("description", "Topic - "+title_url+"the website of the same topic "+title_url+" is synthesized by domain-site-whois.info");
			req.setAttribute("keyword", title_url+",linkout,Domain name information,  Server information, Web site analysis, website traffic details, Website backlinks website IP, website ranking info,topic");
			
//			try {
//				req.getRequestDispatcher("/topic.jsp").forward(req, resp);
//			} catch (ServletException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
	}

}
